<template>
  <el-drawer
    :model-value="isShowPayment"
    size="35%"
    @close="close"
    :close-on-click-modal="false"
  >
    <template #header="{}">
      <div class="flex items-center justify-start">
        <el-icon
          class="w-10 mr-2 cursor-pointer"
          v-if="isShowAdd"
          @click="returnPayment"
          ><ArrowLeftBold
        /></el-icon>
        <div class="flex items-center justify-center flex-1">
          <p>{{ drawerTitle }}</p>
        </div>
      </div>
    </template>
    <div v-if="!isShowPaymentDetail && !isShowAdd">
      <h3 class="mb-4">{{ $t("付款信息") }}</h3>
      <el-card>
        <el-form
          label-position="top"
          :model="state.payInfo"
          style="max-width: 600px"
          v-if="changeShow"
          class="amountForm"
        >
          <el-form-item :label="$t('付款金额')">
            <el-input
              v-model="state.payInfo.amount"
              :placeholder="$t('请输入付款金额')"
            >
              <template #append
                ><el-button @click="assignValue">
                  {{ $t("全部") }}</el-button
                ></template
              >
            </el-input>
          </el-form-item>
        </el-form>
        <div class="detailRow" v-if="!changeShow">
          <span class="rowName">{{ $t("转账金额") }}</span>
          <span class="rowValue"
            >{{ cardInfo.symbol }} {{ state.payInfo.amount }}</span
          >
        </div>
        <div class="detailRow">
          <span class="rowName">{{ $t("付款账户") }}</span>
          <span class="rowValue">{{ cardInfo.bank_card_no }}</span>
        </div>
        <div class="detailRow" v-if="changeShow">
          <span class="rowName">{{ $t("可用余额") }}</span>
          <span class="rowValue"
            >{{ cardInfo.symbol }} {{ cardInfo.total_available }}</span
          >
        </div>
      </el-card>
      <h3 class="mt-4 mb-4">{{ $t("收款信息") }}</h3>
      <!-- 选择收款客户 -->
      <el-form :model="state.receiveInfo" v-if="changeShow">
        <el-form-item>
          <el-select
            v-model="state.receiveInfo.user"
            :placeholder="$t('选择收款客户')"
            style="width: 100%"
            value-key="id"
            @change="userChange"
            :popper-class="customPopperClass"
          >
            <el-option
              v-for="item in state.userList"
              :key="item.id"
              :label="item.company_name"
              :value="item"
            />
            <el-option
              v-if="state.userList.length < 1"
              :label="11"
              :value="false"
            >
              <template #default>
                <div class="flex flex-col items-center justify-center">
                  <div class="mb-2 user">
                    <el-icon><Plus /></el-icon>
                    {{ $t("添加收款人") }}
                  </div>
                  <p>{{ $t("还未添加收款人") }}</p>
                </div>
              </template>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="state.receiveInfo.user">
          <el-select
            v-model="state.receiveInfo.bankCard"
            :placeholder="$t('选择收款账户')"
            style="width: 100%"
            @change="bankChange"
            :popper-class="customBankSelect"
          >
            <el-option
              v-for="item in state.bankCardList"
              :key="item.id"
              :label="item.bank_name"
              :value="item.id"
            >
              <template #default>
                <div
                  class="bankCard"
                  :class="{ active: state.receiveInfo.bankCard === item.id }"
                >
                  <div class="bankRow">
                    <span class="rowName">{{ $t("银行名称") }}</span>
                    <span class="rowValue">{{ item.bank_name }}</span>
                  </div>
                  <div class="bankRow">
                    <span class="rowName">{{ $t("收款账户") }}</span>
                    <span class="rowValue">{{ item.card_number }}</span>
                  </div>
                  <div class="bankRow">
                    <span class="rowName">{{ $t("持卡人姓名") }}</span>
                    <span class="rowValue">{{ item.card_name }}</span>
                  </div>
                </div>
              </template>
            </el-option>
            <el-option
              v-show="state.bankCardList.length < 1"
              :label="11"
              :value="false"
            >
              <template #default>
                <div class="flex flex-col items-center justify-center">
                  <div class="mb-2 user">
                    <el-icon><Plus /></el-icon>
                    {{ $t("添加收款账户") }}
                  </div>
                  <p>{{ $t("还未添加收款账户") }}</p>
                </div>
              </template>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-card v-if="state.receiveInfo.bankCard">
        <div class="detailRow" v-if="!changeShow">
          <span class="rowName">{{ $t("VA-收款客户") }}</span>
          <span class="rowValue">{{ componyName }}</span>
        </div>
        <div
          v-for="(item, index) in bankCardInfoList"
          :key="index"
          class="detailRow"
          v-show="item.isShow"
        >
          <span class="rowName">{{ item.name }}</span>
          <span class="rowValue">{{ item.value }}</span>
        </div>
      </el-card>
      <div class="flex items-center justify-center mt-4">
        <el-button v-if="changeShow" type="danger" class="w-40" @click="next">{{
          $t("下一步")
        }}</el-button>
        <el-button v-else type="danger" class="w-40" @click="submit">{{
          $t("提交")
        }}</el-button>
      </div>
    </div>
    <payDetail
      :orderNo="currentOrderNo"
      :isShowPaymentDetail="isShowPaymentDetail"
    />
    <CreateBankCard
      v-if="isShowAdd"
      :isShowAdd="isShowAdd"
      @closeAddUser="closeAddUser"
    />
  </el-drawer>
  <el-dialog v-model="dialogVisible" :title="$t('安全验证')" width="30%">
    <el-form :model="state.verticalForm" :rules="rules">
      <el-form-item prop="trade_password">
        <el-input
          v-model="state.verticalForm.trade_password"
          :placeholder="$t('VA-请输入支付密码')"
          clearable
          type="password"
          show-password
        />
      </el-form-item>
      <el-form-item prop="email_code">
        <div class="flex items-center justify-between flex-1">
          <el-input
            v-model="state.verticalForm.email_code"
            :placeholder="$t('请输入邮箱验证码')"
            size="large"
          >
          </el-input>

          <el-button
            size="large"
            plain
            type="primary"
            class="w-40 ml-4"
            @click="handleCaptcha"
            v-if="!codesms.disabled"
          >
            {{ $t("获取验证码") }}
          </el-button>
          <el-button
            size="large"
            type="primary"
            class="w-40 ml-4"
            v-else
            disabled
          >
            {{ codesms.count }}{{ $t("秒后重新获取") }}
          </el-button>
        </div>
      </el-form-item>
      <el-form-item prop="google_code" v-if="isVAlid">
        <el-input
          v-model="state.verticalForm.google_code"
          :placeholder="$t('请输入谷歌验证码')"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <div class="flex items-center justify-center w-full">
          <el-button type="primary" @click="confirm" class="w-40">{{
            $t("确认")
          }}</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script setup>
import { ref, watch, onMounted, reactive, computed } from "vue";
import {
  GetVaUserList,
  getBankCardList,
  getVABankCardInfo,
  VATransfer,
} from "@/api/VAAccount";
import payDetail from "./payDetail.vue";
import CreateBankCard from "./createBankCard.vue";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
import { emailSendApi } from "@/api/login/index";
import { useUserStore } from "@/store/modules/user";
import { useMerchantStore } from "@/store/modules/merchant";
const { t } = useI18n();

import { useRouter } from "vue-router";

const router = useRouter();

const useUser = useUserStore();
const useMerchant = useMerchantStore();
const props = defineProps({
  isShowPayment: {
    type: Boolean,
    default: false,
  },
  cardInfo: {
    type: Object,
    default: {},
  },
  currentUserId: {
    type: Number,
    default: 0,
  },
});

const dialogVisible = ref(false);

const isShowAdd = ref(false);

const state = reactive({
  payInfo: {},
  receiveInfo: {
    user: "",
    bankCard: "",
  },
  userList: [],
  bankCardList: [],
  bankCardInfo: {},
  verticalForm: {
    google_code: "",
    email_code: "",
    trade_password: "",
  },
});

const assignValue = () => {
  state.payInfo.amount = props.cardInfo.total_available;
};

const bankCardInfoList = computed(() => {
  let arr = [
    {
      name: `${t("VA-银行账号")}`,
      value: state.bankCardInfo.card_number || "--",
      isShow: true,
    },
    {
      name: `${t("银行所在国家")}`,
      value: state.bankCardInfo.bank_country || "--",
      isShow: true,
    },
    {
      name: `${t("银行名称")}`,
      value: state.bankCardInfo.bank_name || "--",
      isShow: true,
    },
    {
      name: `${t("银行地址")}`,
      value: state.bankCardInfo.bank_address || "--",
      isShow: true,
    },
    {
      name: `${t("持卡人姓名")}`,
      value: state.bankCardInfo.card_name || "--",
      isShow: true,
    },
    {
      name: `${t("持卡人国家")}`,
      value: state.bankCardInfo.card_country || "--",
      isShow: true,
    },
    {
      name: `${t("持卡人地址")}`,
      value: state.bankCardInfo.card_address || "--",
      isShow: true,
    },
    {
      name: `${t("银行账号币种")}`,
      value: state.bankCardInfo.currency || "--",
      isShow: true,
    },
  ];
  return arr;
});

const emit = defineEmits(["close"]);

watch(
  () => props.isShowPayment,
  (newVal) => {
    if (newVal) {
      state.payInfo.amount = "";
    }
  }
);

// 计算属性，根据条件返回不同的类名
const customBankSelect = computed(() => {
  return state.bankCardList.length > 0 ? "customSelect" : "userSelect";
});

const getUserList = async () => {
  const { list } = await GetVaUserList({
    page: 1,
    pagesize: 999999,
    sys_review_status: 1,
  });
  state.userList = list.map((item) => {
    return {
      id: item.id,
      company_name: item.company_name,
    };
  });
};

// 计算属性，根据条件返回不同的类名
const customPopperClass = computed(() => {
  return state.userList.length < 1 ? "userSelect" : "";
});

const componyName = ref("");

const userChange = async (val) => {
  if (!val) {
    state.receiveInfo.user = "";
    const data = {
      isPayment: true,
    };
    router.push({
      path: `/VAAccount/userList/addCustomer`,
      state: data,
    });
  } else {
    componyName.value = val.company_name;
    state.receiveInfo.bankCard = "";
    findUserInfo(val.id);
  }
};

const findUserInfo = async (id) => {
  const { list } = await getBankCardList({ id: id, page: 1, pagesize: 999999 });
  state.bankCardList = list.map((item) => {
    return {
      id: item.id,
      bank_name: item.bank_name,
      card_number: item.card_number,
      card_name: item.card_name,
      company_name: item.company_name,
    };
  });
};

const bankChange = (val) => {
  if (!val) {
    isShowAdd.value = true;
    drawerTitle.value = t("添加收款账户");
    state.receiveInfo.bankCard = "";
  } else {
    getVABankCard(val);
  }
};

const getVABankCard = (val) => {
  getVABankCardInfo({ id: val }).then((res) => {
    state.bankCardInfo = res;
  });
};

// 关闭创建收款账户
const closeAddUser = async (val) => {
  isShowAdd.value = false;
  if (val) {
    state.receiveInfo.bankCard = val;
  }
  await findUserInfo(state.receiveInfo.user.id);
  await getVABankCard(val);
};

const changeShow = ref(true);
const drawerTitle = ref(t("VA-付款"));

// 返回选择付款人
const returnPayment = () => {
  isShowAdd.value = false;
  drawerTitle.value = t("VA-付款");
};

const next = () => {
  if (state.payInfo.amount === "") {
    ElMessage.error("请输入付款金额");
    return;
  }
  if (state.receiveInfo.user === "") {
    ElMessage.error("请选择收款客户");
    return;
  }
  if (state.receiveInfo.bankCard === "") {
    ElMessage.error("请选择收款账户");
    return;
  }
  changeShow.value = false;
  drawerTitle.value = t("VA-确认订单");
};

const submit = () => {
  dialogVisible.value = true;
};

const codesms = reactive({
  disabled: false,
  total: 60,
  count: 0,
});

// 校验
const rules = computed(() => {
  return {
    trade_password: [
      { required: true, message: t("请输入支付密码"), trigger: "blur" },
    ],
    email_code: [
      { required: true, message: t("请输入邮箱验证码"), trigger: "blur" },
    ],
    google_code: [
      { required: true, message: t("请输入谷歌验证码"), trigger: "blur" },
    ],
  };
});

// 倒计时
const timerHandle = () => {
  codesms.count = codesms.total;
  codesms.disabled = true;

  let timer = setInterval(() => {
    if (codesms.count > 1 && codesms.count <= codesms.total) {
      codesms.count--;
    } else {
      codesms.disabled = false;
      clearInterval(timer);
    }
  }, 1000);
};

//发送验证码
const handleCaptcha = async () => {
  try {
    timerHandle();
    const res = await emailSendApi({
      email: useUser.userInfo.userName,
      code_type: "va_assets_transfer",
    });
    ElMessage({
      type: "success",
      message: t("发送验证码成功"),
    });
    // console.log(res);
  } catch (error) {}
};

const isShowPaymentDetail = ref(false);

const currentOrderNo = ref("");

// 确认
const confirm = () => {
  dialogVisible.value = false;
  const params = {
    id: state.receiveInfo.bankCard,
    amount: state.payInfo.amount,
    trade_password: state.verticalForm.trade_password,
    email_code: state.verticalForm.email_code,
  };
  if (isVAlid.value) {
    params.google_code = state.verticalForm.google_code;
  }
  VATransfer(params).then((res) => {
    currentOrderNo.value = res.order_no;
    ElMessage.success(t("付款成功"));
    state.verticalForm = {};
    codesms.disabled = false;
    isShowPaymentDetail.value = true;
    drawerTitle.value = t("订单详情");
  });
};

const isVAlid = ref(false);

const close = () => {
  isShowPaymentDetail.value = false;
  changeShow.value = true;
  state.receiveInfo = {};
  emit("close");
};

onMounted(() => {
  getUserList();
  //   判断是否有谷歌验证
  if (useMerchant.merchantInfo.va > 0) {
    isVAlid.value = true;
  } else {
    isVAlid.value = false;
  }
  if (props.currentUserId) {
    if (state.userList.length > 0) {
      state.receiveInfo.user = state.userList.find(
        (item) => item.id === props.currentUserId
      );
      findUserInfo(props.currentUserId);
    }
  }
});
</script>
<style lang="scss" scoped>
.detailRow {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 1rem;

  .rowName {
    min-width: 30%;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    color: #777;
  }

  .rowValue {
    word-break: break-all;
    text-align: right;
  }
}
.bankRow {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;

  .rowName {
    min-width: 30%;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    color: #777;
  }

  .rowValue {
    word-break: break-all;
    text-align: right;
  }
}
.bankCard {
  border: 1px solid #ccc;
  border-radius: 10px;
  margin: 2%;
  padding: 2%;
}
.active {
  background: #e54c5f;
  color: #fff;
  .rowName {
    color: #fff;
  }
}
.amountForm .el-input-group__append .el-button {
  color: #e54c5f;
  background: #fff;
  border-right: 1px solid #dcdfe6;
  border-top: 1px solid #dcdfe6;
  border-bottom: 1px solid #dcdfe6;
}
.userSelect .el-select-dropdown__item {
  height: 140px !important;
  padding: 0 5px 0 5px !important;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  .user {
    min-width: 110px;
    padding: 0 6px;
    height: 80px;
    border: 1px solid #e54c5f;
    border-radius: 10px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #e54c5f;
    .el-icon {
      font-size: 26px;
      font-weight: 700;
    }
  }
}
</style>
